import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { NavBar, SpinLoading } from 'antd-mobile';
import { LeftOutline } from 'antd-mobile-icons';
import { getDrugDetail } from '../../api/drug';
import type { DrugDetailResponse } from '../../api/drug';
import './index.css';

const DrugDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [drugData, setDrugData] = useState<DrugDetailResponse['result'] | null>(null);
  const [error, setError] = useState<string>('');

  useEffect(() => {
    if (id) {
      fetchDrugDetail(parseInt(id));
    }
  }, [id]);

  const fetchDrugDetail = (drugId: number) => {
    setLoading(true);
    setError('');
    
    getDrugDetail({ id: drugId })
      .then(response => {
        console.log('API响应数据:', response); // 添加调试日志
        console.log('响应状态:', response.status);
        console.log('响应结果:', response.result);
        
        // 修改状态判断逻辑，支持多种成功状态
        if (response.status === 'success' || response.status === '0000' || response.status === '200' || String(response.status) === '200') {
          if (response.result) {
            setDrugData(response.result);
          } else {
            setError('药品数据为空');
          }
        } else {
          // 显示详细的错误信息
          const errorMsg = `状态: ${response.status}, 消息: ${response.message || '未知错误'}`;
          setError(errorMsg);
        }
      })
      .catch(err => {
        console.error('获取药品详情失败:', err);
        setError(`网络错误: ${err.message || '请稍后重试'}`);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const handleBack = () => {
    navigate(-1);
  };

  if (loading) {
    return (
      <div className="drug-detail-loading">
        <SpinLoading color="primary" />
        <p>加载中...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="drug-detail">
        <NavBar onBack={handleBack}>药品详情</NavBar>
        <div className="drug-error">
          <p>错误信息: {error}</p>
          <p>当前药品ID: {id}</p>
          <button onClick={() => id && fetchDrugDetail(parseInt(id))}>重试</button>
          <button onClick={() => console.log('当前状态:', { loading, error, drugData })}>查看状态</button>
        </div>
      </div>
    );
  }

  if (!drugData) {
    return (
      <div className="drug-detail">
        <NavBar onBack={handleBack}>药品详情</NavBar>
        <div className="drug-error">
          <p>未找到药品信息</p>
        </div>
      </div>
    );
  }

  return (
    <div className="drug-detail">
      <NavBar onBack={handleBack} backArrow={<LeftOutline />}>
        药品详情
      </NavBar>
      
      {/* 免责声明 */}
      <div className="drug-disclaimer">
        本模块知识仅供参考，如有需要，请在医生指导下使用
      </div>

      {/* 药品名称 */}
      <div className="drug-name">
        {drugData.name}
      </div>

      {/* 药品信息卡片 */}
      <div className="drug-info-cards">
        {/* 药品成分 */}
        {drugData.component && (
          <div className="info-card">
            <div className="card-title">[药品成分]</div>
            <div className="card-content">{drugData.component}</div>
          </div>
        )}

        {/* 用药禁忌 */}
        <div className="info-card">
          <div className="card-title">[用药禁忌]</div>
          <div className="card-content">
            {drugData.taboo || '无'}
          </div>
        </div>

        {/* 功能主治 */}
        {drugData.effect && (
          <div className="info-card">
            <div className="card-title">[功能主治]</div>
            <div className="card-content">{drugData.effect}</div>
          </div>
        )}

        {/* 用法用量 */}
        {drugData.usage && (
          <div className="info-card">
            <div className="card-title">[用法用量]</div>
            <div className="card-content">{drugData.usage}</div>
          </div>
        )}

        {/* 药品性状 */}
        {drugData.shape && (
          <div className="info-card">
            <div className="card-title">[药品性状]</div>
            <div className="card-content">{drugData.shape}</div>
          </div>
        )}

        {/* 包装规格 */}
        {drugData.packing && (
          <div className="info-card">
            <div className="card-title">[包装规格]</div>
            <div className="card-content">{drugData.packing}</div>
          </div>
        )}

        {/* 不良反应 */}
        {drugData.sideEffects && (
          <div className="info-card">
            <div className="card-title">[不良反应]</div>
            <div className="card-content">{drugData.sideEffects}</div>
          </div>
        )}

        {/* 贮藏 */}
        {drugData.storage && (
          <div className="info-card">
            <div className="card-title">[贮藏]</div>
            <div className="card-content">{drugData.storage}</div>
          </div>
        )}

        {/* 注意事项 */}
        {drugData.minMatter && (
          <div className="info-card">
            <div className="card-title">[注意事项]</div>
            <div className="card-content">{drugData.minMatter}</div>
          </div>
        )}

        {/* 批准文号 */}
        {drugData.approvalNumber && (
          <div className="info-card">
            <div className="card-title">[批准文号]</div>
            <div className="card-content">{drugData.approvalNumber}</div>
          </div>
        )}
      </div>
    </div>
  );
};

export default DrugDetail;
